package com.jic.manager.impl;

import com.jic.common.base.vo.AdminOperate;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.utils.DateUtils;
import com.jic.manager.common.util.BeanUtil;
import com.jic.manager.entity.MerchantWeBank;
import com.jic.manager.entity.SysDept;
import com.jic.manager.enums.DeptTypeEnum;
import com.jic.manager.enums.MerchantStatusType;
import com.jic.manager.mapper.CertificateMapper;
import com.jic.manager.mapper.MerchantWeBankMapper;
import com.jic.manager.mapper.SysDeptMapper;
import com.jic.manager.request.CertificateRequest;
import com.jic.manager.request.MerchantWeBankRequest;
import com.jic.manager.service.MerchantWeBankService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zalando.problem.StatusType;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商户表
 * @author : 
 * @email : 
 * @since : 2020-11-23 05:13:23
 * @version : v1.0.0
 */
@Service
public class MerchantWeBankServiceImpl implements MerchantWeBankService{

    @Autowired
    private MerchantWeBankMapper merchantWeBankMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private CertificateMapper certificateMapper;
    private final Integer successStatus = 3;

    @Override
    public long insert(MerchantWeBank merchantWeBank) {
        long flag = merchantWeBankMapper.insert(merchantWeBank);
        return flag;
    }

    @Override
    public long delete(Long id) {
        return merchantWeBankMapper.delete(id);
    }

    @Override
    public long update(MerchantWeBank merchantWeBank) {
        return merchantWeBankMapper.update(merchantWeBank);
    }

    @Override
    public MerchantWeBank queryByPrimaryKey(Long id){
        return merchantWeBankMapper.queryByPrimaryKey(id);
    }

    @Override
    public List<MerchantWeBank> query(MerchantWeBank merchantWeBank){
        return merchantWeBankMapper.query(merchantWeBank);
    }

    @Override
    public PageResult<MerchantWeBank> queryPage(MerchantWeBankRequest request, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<MerchantWeBank> list = merchantWeBankMapper.queryPage(startIndex, pageQuery.getLimit(), request);
//        list.stream().map(temp->{
//            if(request.getStatusType()==3){
//                temp.set
//            }
//            return temp;
//        }).collect(Collectors.toList());
        long count = merchantWeBankMapper.queryPageCount(request);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public Boolean editMerchantInfo(MerchantWeBankRequest merchantWeBankRequest) {
        AdminOperate  adminOperate = merchantWeBankRequest.getAdminOperate();
        MerchantWeBank merchantWeBank = BeanUtil.copy(merchantWeBankRequest, MerchantWeBank.class);

//        List<MerchantWeBank> merchantList = merchantWeBankMapper.query(new MerchantWeBank(){{
//            setOrgNumber(merchantWeBank.getOrgNumber());
//        }});
//        if(!CollectionUtils.isNotEmpty(merchantList)){
//            throw new RuntimeException("商户编码已存在");
//        }
        if(MerchantStatusType.STATUS_TYPE_1.getType().equals(merchantWeBank.getStatusType())){
            MerchantWeBank merchant = merchantWeBankMapper.queryByPrimaryKey(merchantWeBank.getId());
            if(!merchant.getName().equals(merchantWeBank.getName())){
                SysDept sysDept = new SysDept();
                sysDept.setBusinessId(merchantWeBank.getId());
                sysDept.setDeptName(merchantWeBank.getName());
                sysDept.setUpdater(adminOperate.getOperator());
                sysDept.setUpdaterName(adminOperate.getOperateName());
                sysDeptMapper.updateDeptNameByBusinessId(sysDept);
            }
        }
        if(MerchantStatusType.STATUS_TYPE_2.getType().equals(merchantWeBank.getStatusType())) {
            List<MerchantWeBank> merchantList = merchantWeBankMapper.query(new MerchantWeBank() {{
                setMerchantCode(merchantWeBank.getMerchantCode());
            }});
            merchantList.stream().filter(temp->{
                boolean flag = temp.getId().equals(merchantWeBank.getId())?true:false;
                if(!CollectionUtils.isNotEmpty(merchantList) && flag ){
                    throw new RuntimeException("商户编码已存在");
                }
                return flag;
            });
        }
        merchantWeBank.setUpdater(adminOperate.getOperator());
        merchantWeBank.setUpdaterName(adminOperate.getOperateName());
        long flag = merchantWeBankMapper.update(merchantWeBank);
        return true;
    }

    /**
     * 新增商户 同步新增dept 及资质证书
     * @param merchantWeBankRequest
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long addMerchantInfo(MerchantWeBankRequest merchantWeBankRequest) {
        AdminOperate  adminOperate = merchantWeBankRequest.getAdminOperate();
        MerchantWeBank merchantWeBank = BeanUtil.copy(merchantWeBankRequest, MerchantWeBank.class);
        merchantWeBank.setOrgNumber(DateUtils.getSfmFromDate(new Date()));
        merchantWeBank.setCreator(adminOperate.getOperator());
        merchantWeBank.setCreatorName(adminOperate.getOperateName());
        merchantWeBank.setDeptId(adminOperate.getDeptId());
        long flag = merchantWeBankMapper.insert(merchantWeBank);

        List<CertificateRequest> certificateList = new ArrayList<>();
        //新增五条数据 分别为  营业执照 开户银行许可证 法人身份证 企业基本情况介绍  商户入驻信息表
        for(int i=0;i<5;i++){
            CertificateRequest certificate = new CertificateRequest();
            certificate.setMerchantId(merchantWeBank.getId());
            certificate.setCreator(adminOperate.getOperator());
            certificate.setCreatorName(adminOperate.getOperateName());
            certificate.setDeptId(adminOperate.getDeptId());
            if(i==0){
                certificate.setCertificateName("营业执照");
                certificate.setCertificateType("1");
            }else if(i==1){
                certificate.setCertificateName("开户银行许可证");
                certificate.setCertificateType("2");
            }else if(i==2){
                certificate.setCertificateName("法人身份证");
                certificate.setCertificateType("3");
            }else if(i==3){
                certificate.setCertificateName("企业基本情况介绍");
                certificate.setCertificateType("4");
            }else if(i==4){
                certificate.setCertificateName("商户入驻信息表");
                certificate.setCertificateType("5");
            }
            certificateList.add(certificate);
        }
        certificateMapper.insertMCertificateList(certificateList);
        return merchantWeBank.getId();
    }

    /**
     * 商户提交审核
     * @param request
     * @return
     */
    @Override
    public Boolean submitReview(MerchantWeBankRequest request) {
        AdminOperate adminOperate = request.getAdminOperate();
        MerchantWeBank merchantWeBank = BeanUtil.copy(request, MerchantWeBank.class);
        merchantWeBank.setUpdater(adminOperate.getOperator());
        merchantWeBank.setUpdaterName(adminOperate.getOperateName());
        if(MerchantStatusType.STATUS_TYPE_1.getType().equals(merchantWeBank.getStatusType().toString())){
            merchantWeBank.setRetailStatus(2);
        }else if(MerchantStatusType.STATUS_TYPE_2.getType().equals(merchantWeBank.getStatusType().toString())){
            merchantWeBank.setWorkStatus(2);
        }else if(MerchantStatusType.STATUS_TYPE_3.getType().equals(merchantWeBank.getStatusType().toString())){
            merchantWeBank.setManagerStatus(2);
        }
        merchantWeBankMapper.update(merchantWeBank);
        return true;
    }

    /**
     * 商户审核
     * @param request
     * @return
     */
    @Override
    public Boolean merchantReview(MerchantWeBankRequest request) {
        AdminOperate adminOperate = request.getAdminOperate();
        MerchantWeBank merchantWeBank = BeanUtil.copy(request, MerchantWeBank.class);
        merchantWeBank.setUpdater(adminOperate.getOperator());
        merchantWeBank.setUpdaterName(adminOperate.getOperateName());
        boolean flag = false;
        MerchantWeBank merchant = merchantWeBankMapper.queryByPrimaryKey(request.getId());
        if(MerchantStatusType.STATUS_TYPE_1.getType().equals(merchantWeBank.getStatusType().toString())){
            if(merchantWeBank.getRetailStatus().equals(successStatus)){
                merchantWeBank.setStatusType(2);
                merchantWeBank.setWorkStatus(1);
            }
        }else if(MerchantStatusType.STATUS_TYPE_2.getType().equals(merchantWeBank.getStatusType().toString())){
            if(merchantWeBank.getWorkStatus().equals(successStatus)){
                merchantWeBank.setStatusType(3);
                merchantWeBank.setManagerStatus(1);
                merchantWeBank.setSettledTime(new Date());
                flag = true;
            }
        }
        merchantWeBankMapper.update(merchantWeBank);
        if(flag){
            SysDept sysDept = new SysDept();
            sysDept.setBusinessId(merchantWeBank.getId());
            sysDept.setPid(1L);
            sysDept.setDeptName(merchant.getName());
            sysDept.setStatus("0");
            sysDept.setDeptType(DeptTypeEnum.MERCHANT_TYPE.getType());
            sysDept.setCreator(adminOperate.getOperator());
            sysDept.setCreatorName(adminOperate.getOperateName());
            sysDept.setCreateTime(new Date());
            sysDeptMapper.insert(sysDept);
        }
        return true;
    }

    /**
     * 撤销提交
     * @param request
     * @return
     */
    @Override
    public Boolean revokeReview(MerchantWeBankRequest request) {
        AdminOperate adminOperate = request.getAdminOperate();
        MerchantWeBank merchantWeBank = BeanUtil.copy(request, MerchantWeBank.class);
        merchantWeBank.setUpdater(adminOperate.getOperator());
        merchantWeBank.setUpdaterName(adminOperate.getOperateName());
        if(MerchantStatusType.STATUS_TYPE_1.getType().equals(merchantWeBank.getStatusType().toString())){
            merchantWeBank.setRetailStatus(1);
        }else if(MerchantStatusType.STATUS_TYPE_2.getType().equals(merchantWeBank.getStatusType().toString())){
            merchantWeBank.setWorkStatus(1);
        }else if(MerchantStatusType.STATUS_TYPE_3.getType().equals(merchantWeBank.getStatusType().toString())){
            merchantWeBank.setManagerStatus(1);
        }
        merchantWeBankMapper.update(merchantWeBank);
        return true;
    }

    /**
     * 批量提交审核
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean batchSubmitReview(MerchantWeBankRequest request) {
        AdminOperate adminOperate = request.getAdminOperate();
        request.setUpdater(adminOperate.getOperator());
        request.setUpdaterName(adminOperate.getOperateName());
        if(MerchantStatusType.STATUS_TYPE_1.getType().equals(request.getStatusType().toString())){
            request.setRetailStatus(2);
        }else if(MerchantStatusType.STATUS_TYPE_2.getType().equals(request.getStatusType().toString())){
            request.setWorkStatus(2);
        }else if(MerchantStatusType.STATUS_TYPE_3.getType().equals(request.getStatusType().toString())){
            request.setManagerStatus(2);
        }
        merchantWeBankMapper.batchUpdateStatus(request);
        return true;
    }

    /**
     * 批量审核
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean batchMerchantReview(MerchantWeBankRequest request) {
        AdminOperate adminOperate = request.getAdminOperate();
        request.setUpdater(adminOperate.getOperator());
        request.setUpdaterName(adminOperate.getOperateName());
        MerchantWeBank merchant = merchantWeBankMapper.queryByPrimaryKey(request.getId());
        final boolean[] flag = {false};
        List<SysDept> deptList = new ArrayList<>();
        request.getRequestList().stream().map(temp->{
            if(MerchantStatusType.STATUS_TYPE_1.getType().equals(request.getStatusType().toString())){
                if(request.getRetailStatus().equals(successStatus)){
                    request.setStatusType(2);
                    request.setWorkStatus(1);
                }
            }else if(MerchantStatusType.STATUS_TYPE_2.getType().equals(request.getStatusType().toString())){
                if(request.getWorkStatus().equals(successStatus)){
                    request.setStatusType(3);
                    request.setManagerStatus(1);
                    request.setSettledTime(new Date());
                    flag[0] = true;
                    SysDept sysDept = new SysDept();
                    sysDept.setBusinessId(request.getId());
                    sysDept.setPid(1L);
                    sysDept.setDeptName(merchant.getName());
                    sysDept.setStatus("0");
                    sysDept.setDeptType(DeptTypeEnum.MERCHANT_TYPE.getType());
                    sysDept.setCreator(adminOperate.getOperator());
                    sysDept.setCreatorName(adminOperate.getOperateName());
                    sysDept.setCreateTime(new Date());
                    deptList.add(sysDept);
                }
            }
            return temp;
        }).collect(Collectors.toList());
        merchantWeBankMapper.batchUpdateStatus(request);
        if(flag[0]){
            sysDeptMapper.foreachInsert(deptList);
        }
        return true;
    }

}